<template>
    <div class="electric-chart" ref="chartRef"></div>
</template>

<script>
import * as echarts from 'echarts';
import request from "@/utils/request";
import TotalChargeChart from "@/views/TotalChargeChart.vue";

export default {
    name: 'ElectricDynamicChart',
    components: {TotalChargeChart},
    data() {
        return {
            myChart: null,
            electricData: {},
            lastElectricCharge: {},
            maxDataCount: 20,
            requestInterval: null,
            colorList: [
                '#43a047', '#2196f3', '#ff9800', '#f44336', '#9c27b0',
                '#00bcd4', '#795548', '#607d8b', '#ffeb3b', '#18ffff'
            ]
        };
    },
    mounted() {
        this.initChart();
        this.startRequest();
    },
    beforeUnmount() {
        if (this.requestInterval) clearInterval(this.requestInterval);
        if (this.myChart) this.myChart.dispose();
        window.removeEventListener('resize', this.handleResize);
    },
    methods: {
        initChart() {
            const chartDom = this.$refs.chartRef;
            this.myChart = echarts.init(chartDom);
            this.myChart.setOption(this.getChartOption());
            window.addEventListener('resize', this.handleResize);
        },

        handleResize() {
            if (this.myChart) this.myChart.resize();
        },

        getChartOption() {
            const series = Object.entries(this.electricData).map(([id, item], index) => {
                const color = this.colorList[index % this.colorList.length];
                return {
                    id: `electric_${id}`,
                    name: item.name,
                    type: 'line',
                    showSymbol: false,
                    smooth: true,
                    lineStyle: {width: 2, color},
                    emphasis: {
                        lineStyle: {width: 4, color: `${color}ff`},
                        focus: 'series'
                    },
                    data: item.data,
                    triggerLineEvent: true,
                    tooltip: {
                        trigger: 'item',
                        triggerOn: 'mousemove|click'
                    }
                };
            });

            return {
                title: {text: '多电器实时功率监测', left: 'center'},
                tooltip: {
                    trigger: 'item',
                    triggerOn: 'mousemove',
                    axisPointer: {
                        type: 'line',
                        lineStyle: {
                            color: '#43a047',
                            width: 1,
                            type: 'dashed'
                        }
                    },
                    formatter: this.formatTooltip,
                    padding: 10,
                    backgroundColor: 'rgba(255, 255, 255, 0.95)',
                    borderColor: '#43a047',
                    borderWidth: 1,
                    textStyle: {fontSize: 12}
                },
                legend: {
                    top: 'bottom',
                    left: 'center',
                    textStyle: {fontSize: 11, color: '#333'}, // 明确设置图例文字颜色
                    itemWidth: 12,
                    itemHeight: 6,
                    padding: [0, 10]
                },
                xAxis: {
                    type: 'time',
                    splitLine: {show: false},
                    axisLabel: {formatter: '{hh}:{mm}:{ss}', color: '#666'}, // 明确设置x轴标签颜色
                    axisLine: {lineStyle: {color: '#eee'}}
                },
                yAxis: {
                    type: 'value',
                    boundaryGap: [0, '10%'],
                    splitLine: {
                        show: true,
                        lineStyle: {color: 'rgba(240, 240, 240, 0.5)'}
                    },
                    name: '功率 (kW)',
                    nameTextStyle: {
                        margin: 10,
                        color: '#333', // 关键：明确设置y轴名称颜色为黑色
                        fontSize: 13
                    },
                    axisLine: {lineStyle: {color: '#eee'}},
                    axisLabel: {color: '#666'} // 明确设置y轴标签颜色
                },
                series: series,
                grid: {
                    left: '8%',
                    right: '5%',
                    bottom: '25%',
                    top: '10%',
                    backgroundColor: 'transparent'
                }
            };
        },

        formatTooltip(params) {
            const {seriesName, value, color} = params;
            const date = new Date(value[0]);
            const timeStr = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
            return `
                <div style="display: flex; align-items: center; margin-bottom: 4px;">
                    <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${color}; margin-right: 6px;"></span>
                    <strong style="color: #333;">${seriesName}</strong>
                </div>
                <div style="color: #666; font-size: 11px;">时间：${timeStr}</div>
                <div style="color: #333; font-weight: 500;">功率：${value[1].toFixed(2)} kW</div>
            `;
        },

        startRequest() {
            this.fetchElectricData();
            this.requestInterval = setInterval(() => this.fetchElectricData(), 1000);
        },

        async fetchElectricData() {
            try {
                const response = await request.get('/api/electric/list');
                if (response.data.code !== '200' || !response.data.data.length) {
                    console.warn('接口返回数据异常', response.data);
                    return;
                }

                const currentTime = new Date().toISOString();
                const electricList = response.data.data;

                electricList.forEach(item => {
                    const {id, electricTypeName, electricCharge} = item;
                    let power = 0;
                    if (this.lastElectricCharge[id] !== undefined) {
                        const chargeDiff = electricCharge - this.lastElectricCharge[id];
                        power = chargeDiff / (1 / 3600);
                    }
                    this.lastElectricCharge[id] = electricCharge;

                    const dataPoint = [currentTime, power];

                    if (!this.electricData[id]) {
                        this.electricData[id] = {
                            name: electricTypeName,
                            data: []
                        };
                    }

                    const electricItem = this.electricData[id];
                    electricItem.data.push(dataPoint);
                    if (electricItem.data.length > this.maxDataCount) {
                        electricItem.data.shift();
                    }
                });

                this.updateChart();
            } catch (error) {
                console.error('获取电力数据失败', error);
            }
        },

        updateChart() {
            if (this.myChart) {
                const option = this.getChartOption();
                this.myChart.setOption(option, true);
            }
        }
    }
};
</script>

<style scoped>
.electric-chart {
    width: 100%;
    height: 390px;
}

::v-deep .echarts-legend-item:hover {
    cursor: pointer;
    opacity: 0.8;
}

::v-deep .echarts-tooltip {
    z-index: 9999 !important;
}
</style>